﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using TRL.DataAccessLayer;

namespace TRL.OnlineSignUp
{
    public class SignUpStep1 : IHttpHandler
    {

        /// <summary>
        /// You will need to configure this handler in the Web.config file of your 
        /// web and register it with IIS before being able to use it. For more information
        /// see the following link: http://go.microsoft.com/?linkid=8101007
        /// </summary>

        public bool IsReusable
        {
            // Return false in case your Managed Handler cannot be reused for another request.
            // Usually this would be false in case you have some state information preserved per request.
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            var r = context.Request;
                        
            // Validate form. JQUery Validator is used to provide nice client side validation,
            // so ugly server-side validation is justified
            string[] requiredFields = { "acceptWaiver", "firstName", "lastName" };
            var missingFields = new List<string>();
            foreach (var field in requiredFields)
            {
                if (String.IsNullOrWhiteSpace(r.Params[field]))
                {
                    missingFields.Add(field);
                }            
            }
            if (missingFields.Count > 0)
            {
                context.Response.Write("The following required fields are missing: " + String.Join(", ", missingFields.ToArray()));
                return;
            }

            var dc = new DataClasses1DataContext();

            // Extract only digits from the phone number field
            var phoneNumberTrimmed = Regex.Replace(r.Params["phoneNumber"], @"\D", "");

            // DOB not displayed!
            // Note we are not storing if the person choose new or renewal. Should we? Probably.
            var membershipType = Int32.Parse(r.Params["membershipType"]);
            var interimMembership = new InterimMembership
            {
                membershipType = membershipType,
                firstName = r.Params["firstName"],
                lastName = r.Params["lastName"],
                gender = r.Params["gender"],
                address = r.Params["address"],
                city = r.Params["city"],
                state = r.Params["state"],
                postalCode = r.Params["postalCode"],
                phoneNumber = phoneNumberTrimmed,
                email = r.Params["email"],
                shirtSize = r.Params["shirtSize"],
                occupation = r.Params["occupation"],
                forumUsername = r.Params["forumUsername"],
                secondFirstName = r.Params["secondFirstName"],
                secondLastName = r.Params["secondLastName"],
                secondGender = r.Params["secondPersonGender"],
                secondShirtSize = r.Params["secondPersonShirtSize"],
                secondEmail = r.Params["secondEmail"],
                secondOccupation = r.Params["secondOccupation"],
                secondForumUsername = r.Params["secondForumUsername"],
                IPAddressFrom = r.UserHostAddress,
                userAgent = r.UserAgent,
                addedOn = DateTime.Now,
                newOrRenewal = r.Params["newOrRenewal"].ToCharArray()[0]
            };

            DateTime dob;
            if (DateTime.TryParse(r.Params["DOB"].ToString(), out dob))
                interimMembership.dob = dob;
            DateTime secondDob;
            if (DateTime.TryParse(r.Params["secondDob"].ToString(), out secondDob))
                interimMembership.secondDob = secondDob;

            var paypal = new NVPAPICaller();
            string retMsg = "";
            string token = "";

            double paymentAmt;
            string type;
            if (membershipType == 1)
            {
                paymentAmt = 30.00;
                type = "Individual";
            }
            else
            {
                paymentAmt = 50.00;
                type = "Family";
            }

            interimMembership.amountPaid = (decimal?)paymentAmt;
            string amt = paymentAmt.ToString();

            bool ret = paypal.MarkExpressCheckout(amt, type, interimMembership.email, 
                            ref token, ref retMsg);
            if (ret)
            {
                interimMembership.paypalToken = token;
                try
                {
                    dc.InterimMemberships.InsertOnSubmit(interimMembership);
                    dc.SubmitChanges();
                }
                catch (Exception ex)
                {
                    context.Response.Redirect(String.Format("APIError.aspx?desc={0}", 
                        context.Server.UrlEncode(ex.Message)));
                }
            

                context.Response.Redirect(retMsg);
            }
            else
            {
                context.Response.Redirect("APIError.aspx?" + retMsg);
            }
        }

    }

}

